package com.nervenets.web.controller.handler.admin.user;

import com.nervenets.web.controller.handler.SessionHandler;
import com.nervenets.web.enumeration.AuthStatus;
import com.nervenets.web.enumeration.Role;
import com.nervenets.web.hibernate.domain.user.Bank;
import com.nervenets.web.redis.domain.user.UserStored;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class BankListForManagerHandler extends SessionHandler<BankListForManagerParams> {
    @Override
    public ArrayList<Role> allowRoles() {
        return Role.administrator();
    }

    @Override
    public boolean needLog() {
        return false;
    }

    @Override
    public String handle(BankListForManagerParams params, HttpServletRequest request) throws Exception {
        String hql = "from Bank where id > 0 ";
        List<Object> objects = new ArrayList<>();

        switch (params.getAuth()) {
            case 0:
                break;
            case 1:
                hql += "and authStatus = ? ";
                objects.add(AuthStatus.failed);
                break;
            case 2:
                hql += "and authStatus = ? ";
                objects.add(AuthStatus.checking);
                break;
            case 3:
                hql += "and authStatus = ? ";
                objects.add(AuthStatus.success);
                break;
        }

        final BigDecimal countOfByHql = userDao.getCountOfByHql(hql, objects);
        hql += "order by id desc ";
        List<Bank> banks = userDao.getAllObjectsByHql(hql, objects, params.getStart(), params.getLimit());
        HashMap<Long, UserStored> userStoredHashMap = new HashMap<>();
        for (Bank bank : banks) {
            if (!userStoredHashMap.containsKey(bank.getUserId())) {
                userStoredHashMap.put(bank.getUserId(), globalService.getUser(bank.getUserId()));
            }
        }
        return successMessage(banks,
                new KeyValue("start", params.getStart()),
                new KeyValue("total", countOfByHql.intValue()),
                new KeyValue("users", userStoredHashMap));
    }

    @Override
    public String result() throws Exception {
        return successMessage("银行列表");
    }
}
